<template>
  <view v-show="showPopup" class="red-packet" @touchmove.stop.prevent="clear">
    <uni-transition
      :mode-class="['fade']"
      class="red-packet__mask"
      :duration="duration"
      :show="showTrans"
      @tap="onTap"
    />
    <uni-transition
      :mode-class="['zoom-out', 'fade']"
      class="red-packet__transition"
      :duration="300"
      :show="showTrans"
      @tap="onTap"
    >
      <view class="red-packet__wrapper-box" @tap.stop="clear">
        <image
          v-show="openType === 1 && !opened"
          src="./images/packet.png"
          class="red-packet__packet"
          @click="openPacket"
        ></image>
        <block v-if="opened || openType === 2">
          <image class="red-packet__background" src="./images/background.png"></image>
          <view class="red-packet__content">
            <view class="red-packet__content__title">恭喜你获得</view>
            <view class="red-packet__content__object">
              <block v-if="openType === 2">
                <image class="image" :src="$wanlshop.oss(item.image, 80, 80)" v-if="item.type == 1"></image>
                <view class="money" v-else-if="item.type == 2">
                  {{ packetPrice || 0 }}<text class="sign">元</text>
                </view>
                <view class="money" v-else-if="item.type == 3">
                  {{ item.total_num || 0 }}<text class="sign">{{ integralName }}</text>
                </view>
              </block>
              <view v-else class="money"> {{ price || 0 }}<text class="sign">元</text> </view>
            </view>
            <block v-if="openType === 2">
              <view class="red-packet__content__info" v-if="item.type == 1">实物奖励，已存入中奖记录</view>
              <view class="red-packet__content__info" v-else-if="item.type == 2">
                红包奖励需分享{{ needShare }}人可得
              </view>
              <view class="red-packet__content__info" v-else-if="item.type == 3">
                {{ integralName }}奖励，已存入中奖记录
              </view>
            </block>
            <view v-else class="red-packet__content__info"> </view>
            <view class="red-packet__look-btn" @click="onIndex">
              <block v-if="openType === 2">
                <text>{{ ['去查看', '去分享', '去使用'][item.type - 1] }}</text>
              </block>
              <block v-else>
                <text>去使用</text>
              </block>
            </view>
          </view>
        </block>
        <view class="red-packet__close" @click="close"></view>
      </view>
    </uni-transition>
  </view>
</template>

<script>
import uniTransition from '../uni-transition/uni-transition.vue';
import api from '@/common/request/request';
import { mapGetters } from 'vuex';

/**
 * PopUp 弹出层
 * @description 弹出层组件，为了解决遮罩弹层的问题
 * @tutorial https://ext.dcloud.net.cn/plugin?id=329
 * @property {String} type = [top|center|bottom] 弹出方式
 * 	@value top 顶部弹出
 * 	@value center 中间弹出
 * 	@value bottom 底部弹出
 * @property {Boolean} animation = [ture|false] 是否开启动画
 * @property {Boolean} maskClick = [ture|false] 蒙版点击是否关闭弹窗
 * @event {Function} change 打开关闭弹窗触发，e=false
 */

export default {
  name: 'RedPacket',
  components: {
    uniTransition,
  },
  model: {
    prop: 'show',
    event: 'change',
  },
  props: {
    item: {
      type: Object,
      default: () => ({
        image: '',
        type: 1,
        total_num: 0,
      }),
    },
    openType: {
      type: Number,
      default: () => 1,
    },
    show: {
      type: Boolean,
      default: () => false,
    },
  },
  data() {
    return {
      duration: 300,
      ani: ['zoom-out', 'fade'],
      showPopup: false,
      showTrans: false,
      maskClick: false,
      type: 'center',
      animation: true,
      opened: false,
      price: 0,
    };
  },
  computed: {
    needShare() {
      if (!this.item.ext) return 0;
      const ext = JSON.parse(this.item.ext);
      const keys = Object.keys(ext).map(key => Number(key));
      return String(Math.max(...keys));
    },
    packetPrice() {
      if (!this.item.ext) return 0;
      const ext = JSON.parse(this.item.ext);
      const keys = Object.keys(ext).map(key => Number(key));
      return ext[String(Math.max(...keys))];
    },
    ...mapGetters('common', ['integralName']),
  },
  watch: {
    show: {
      handler(newVal) {
        console.log(newVal);
        if (newVal) {
          this.open();
        } else this.close();
      },
    },
  },
  created() {
    if (this.animation) {
      this.duration = 300;
    } else {
      this.duration = 0;
    }
  },
  methods: {
    openPacket() {
      if (this.openType == 1) {
        api
          .post({
            url: '/wanlshop/redpacket/receive',
          })
          .then(res => {
            this.price = res;
            this.opened = true;
            this.playAudio();
          });
      } else {
        this.opened = true;
      }
    },
    clear(e) {
      // TODO nvue 取消冒泡
      e.stopPropagation();
    },
    playAudio() {
      console.log('播放音频');
      let src = '/static/voice/ok.mp3';
      //实例化声音
      const Audio = uni.createInnerAudioContext();
      Audio.autoplay = true;
      Audio.src = src; //音频地址
      Audio.play(); //执行播放
      Audio.onError(res => {
        console.log(res.errMsg);
        console.log(res.errCode);
        alert(res.errMsg);
        alert(res.errCode);
      });
      Audio.onPause(function () {
        console.log('end');
        Audio.destroy();
      });
    },
    open() {
      this.showPopup = true;
      this.$nextTick(() => {
        clearTimeout(this.timer);
        // clearTimeout(this.timer);
        // this.timer = setTimeout(() => {
        //   this.showTrans = true;
        // }, 50);
        this.showTrans = true;
      });
      this.$emit('change', true);
    },
    onIndex() {
      this.close();
      if (this.item.type == 3) {
        uni.setTabBarStyle({
          backgroundColor: '#ffffff',
          borderStyle: 'white',
        });
        uni.navigateTo({
          url: '/pages/apps/integrals/index',
        });
      } else if (this.openType == 1) {
        this.close();
      } else {
        this.$wanlshop.to('/pages/user/winLog');
      }
    },
    close(type) {
      this.showTrans = false;
      this.$nextTick(() => {
        clearTimeout(this.timer);
        this.timer = setTimeout(() => {
          this.showPopup = false;
          this.$emit('change', false);
        }, 300);
      });
    },
    onTap() {
      if (!this.maskClick) return;
      this.close();
    },
  },
};
</script>
<style scoped lang="scss">
.red-packet {
  position: fixed;
  /* #ifdef H5 */
  top: var(--window-top);
  /* #endif */
  /* #ifndef H5 */
  top: 0;
  /* #endif */
  bottom: 0;
  left: 0;
  right: 0;
  /* #ifndef APP-NVUE */
  z-index: 9999;
  /* #endif */
  &__mask {
    position: fixed;
    bottom: 0;
    top: 0;
    left: 0;
    right: 0;
    background-color: rgba(0, 0, 0, 0.5);
  }
  &__transition {
    position: fixed;
    /* #ifndef APP-NVUE */
    display: flex;
    flex-direction: column;
    /* #endif */
    bottom: 0;
    left: 0;
    right: 0;
    top: 0;
    justify-content: center;
    align-items: center;
  }
  &__wrapper-box {
    display: block;
    position: relative;
  }
  &__packet {
    width: 278px;
    height: 334px;
  }
  &__background {
    display: block;
    width: 746rpx;
    height: 792rpx;
    position: absolute;
    z-index: -1;
  }
  &__content {
    display: block;
    width: 746rpx;
    height: 792rpx;
    color: #e02020;
    font-weight: 600;
    z-index: 9;
    position: relative;
    overflow: hidden;
    &__title {
      font-size: 24px;
      line-height: 33px;
      margin: 115px auto 0;
      text-align: center;
    }
    &__info {
      margin-top: 73px;
      text-align: center;
      font-weight: 500;
      line-height: 20px;
      height: 20px;
      overflow: hidden;
    }
    &__object {
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      font-size: 48px;
      line-height: 67px;
      .money {
        .sign {
          font-size: 16px;
          line-height: 22px;
          margin-left: 4px;
        }
      }
      .image {
        height: 80px;
        width: 80px;
        display: block;
        position: relative;
        top: -4px;
      }
    }
  }
  &__look-btn {
    overflow: hidden;
    margin: 77px auto 0;
    width: 169px;
    height: 56px;
    font-weight: 500;
    font-size: 18px;
    text-align: center;
    background-repeat: no-repeat;
    background-size: 100% auto;
    background-image: url("data:image/svg+xml,%3C?xml version='1.0' encoding='UTF-8'?%3E %3Csvg width='169px' height='56px' viewBox='0 0 169 56' version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'%3E %3C!-- Generator: Sketch 60 (88103) - https://sketch.com --%3E %3Ctitle%3E矩形备份%3C/title%3E %3Cdesc%3ECreated with Sketch.%3C/desc%3E %3Cdefs%3E %3ClinearGradient x1='50%25' y1='0%25' x2='50%25' y2='100%25' id='linearGradient-1'%3E %3Cstop stop-color='%23FEEEB8' offset='0%25'%3E%3C/stop%3E %3Cstop stop-color='%23FDB72B' offset='100%25'%3E%3C/stop%3E %3C/linearGradient%3E %3Crect id='path-2' x='6' y='4' width='157' height='44' rx='22'%3E%3C/rect%3E %3Cfilter x='-6.4%25' y='-18.2%25' width='112.7%25' height='145.5%25' filterUnits='objectBoundingBox' id='filter-3'%3E %3CfeOffset dx='0' dy='2' in='SourceAlpha' result='shadowOffsetOuter1'%3E%3C/feOffset%3E %3CfeGaussianBlur stdDeviation='3' in='shadowOffsetOuter1' result='shadowBlurOuter1'%3E%3C/feGaussianBlur%3E %3CfeColorMatrix values='0 0 0 0 0.802055027 0 0 0 0 0.802055027 0 0 0 0 0.802055027 0 0 0 0.3 0' type='matrix' in='shadowBlurOuter1'%3E%3C/feColorMatrix%3E %3C/filter%3E %3Cfilter x='-7.6%25' y='-22.7%25' width='115.3%25' height='154.5%25' filterUnits='objectBoundingBox' id='filter-4'%3E %3CfeGaussianBlur stdDeviation='3' in='SourceAlpha' result='shadowBlurInner1'%3E%3C/feGaussianBlur%3E %3CfeOffset dx='-6' dy='-6' in='shadowBlurInner1' result='shadowOffsetInner1'%3E%3C/feOffset%3E %3CfeComposite in='shadowOffsetInner1' in2='SourceAlpha' operator='arithmetic' k2='-1' k3='1' result='shadowInnerInner1'%3E%3C/feComposite%3E %3CfeColorMatrix values='0 0 0 0 1 0 0 0 0 0.765473215 0 0 0 0 0.285918445 0 0 0 1 0' type='matrix' in='shadowInnerInner1' result='shadowMatrixInner1'%3E%3C/feColorMatrix%3E %3CfeGaussianBlur stdDeviation='2.5' in='SourceAlpha' result='shadowBlurInner2'%3E%3C/feGaussianBlur%3E %3CfeOffset dx='-6' dy='-5' in='shadowBlurInner2' result='shadowOffsetInner2'%3E%3C/feOffset%3E %3CfeComposite in='shadowOffsetInner2' in2='SourceAlpha' operator='arithmetic' k2='-1' k3='1' result='shadowInnerInner2'%3E%3C/feComposite%3E %3CfeColorMatrix values='0 0 0 0 1 0 0 0 0 0.749983237 0 0 0 0 0.225438262 0 0 0 1 0' type='matrix' in='shadowInnerInner2' result='shadowMatrixInner2'%3E%3C/feColorMatrix%3E %3CfeMerge%3E %3CfeMergeNode in='shadowMatrixInner1'%3E%3C/feMergeNode%3E %3CfeMergeNode in='shadowMatrixInner2'%3E%3C/feMergeNode%3E %3C/feMerge%3E %3C/filter%3E %3C/defs%3E %3Cg id='最新商城模板' stroke='none' stroke-width='1' fill='none' fill-rule='evenodd'%3E %3Cg id='乾豆弹窗' transform='translate(-103.000000, -435.000000)'%3E %3Cg id='编组-3' transform='translate(103.000000, 435.000000)'%3E %3Cg id='矩形备份'%3E %3Cuse fill='black' fill-opacity='1' filter='url(%23filter-3)' xlink:href='%23path-2'%3E%3C/use%3E %3Cuse fill='url(%23linearGradient-1)' fill-rule='evenodd' xlink:href='%23path-2'%3E%3C/use%3E %3Cuse fill='black' fill-opacity='1' filter='url(%23filter-4)' xlink:href='%23path-2'%3E%3C/use%3E %3C/g%3E %3C/g%3E %3C/g%3E %3C/g%3E %3C/svg%3E");
    text {
      display: block;
      margin-top: 13px;
    }
  }
  &__close {
    width: 26px;
    height: 26px;
    margin: 18px auto 0;
    background-size: 100% auto;
    background-repeat: no-repeat;
    background-image: url("data:image/svg+xml,%3C?xml version='1.0' encoding='UTF-8'?%3E %3Csvg width='26px' height='26px' viewBox='0 0 26 26' version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'%3E %3C!-- Generator: Sketch 60 (88103) - https://sketch.com --%3E %3Ctitle%3E关闭%3C/title%3E %3Cdesc%3ECreated with Sketch.%3C/desc%3E %3Cg id='最新商城模板' stroke='none' stroke-width='1' fill='none' fill-rule='evenodd' fill-opacity='0.5'%3E %3Cg id='开红包' transform='translate(-174.000000, -540.000000)' fill='%23FFFFFF' fill-rule='nonzero'%3E %3Cg id='关闭' transform='translate(174.000000, 540.000000)'%3E %3Cpath d='M13.0000166,2.776904e-06 C5.82009559,2.776904e-06 -1.11826e-05,5.82010955 -1.11826e-05,13.0000306 C-1.11826e-05,20.1799516 5.82009559,26.0000584 13.0000166,26.0000584 C20.1799377,26.0000584 26.0000445,20.1799516 26.0000445,13.0000306 C26.0000445,5.82010955 20.1799377,2.776904e-06 13.0000166,2.776904e-06 Z M13.0000166,24.7000417 C6.53772182,24.7000417 1.30000556,19.4623254 1.30000556,13.0000306 C1.30000556,6.53773578 6.53772182,1.30001952 13.0000166,1.30001952 C19.4623115,1.30001952 24.7000277,6.53773578 24.7000277,13.0000306 C24.7000277,19.4623254 19.4623115,24.7000417 13.0000166,24.7000417 Z M18.9748261,7.02522111 C18.7213259,6.77172091 18.3092246,6.77172091 18.0557261,7.02522111 L13.0000278,12.0809194 L7.94432955,7.02522111 C7.69082935,6.77172091 7.27872801,6.77172091 7.02522949,7.02522111 C6.7717293,7.2787213 6.7717293,7.69082264 7.02522949,7.94432116 L12.0809278,13.0000194 L7.02522949,18.0557177 C6.7717293,18.3092179 6.7717293,18.7213192 7.02522949,18.9748177 C7.27872969,19.2283179 7.69083103,19.2283179 7.94432955,18.9748177 L13.0000278,13.9191195 L18.0557261,18.9748177 C18.3092263,19.2283179 18.7213276,19.2283179 18.9748261,18.9748177 C19.2283263,18.7213176 19.2283263,18.3092162 18.9748261,18.0557177 L13.9191279,13.0000194 L18.9748261,7.94432116 C19.2283263,7.69082097 19.2283263,7.27871963 18.9748261,7.02522111 Z' id='形状'%3E%3C/path%3E %3C/g%3E %3C/g%3E %3C/g%3E %3C/svg%3E");
  }
}
</style>
